package com.jq.aution.service.impl;

import com.jq.aution.mapper.ProductBidInfoMapper;
import com.jq.aution.model.ProductBidInfo;
import com.jq.aution.model.ProductBidInfoExample;
import com.jq.aution.service.ProductBidInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductBidInfoServiceImpl implements ProductBidInfoService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ProductBidInfoServiceImpl.class);

    @Autowired
    ProductBidInfoMapper productBidInfoMapper;

    @Autowired
    private SimpMessageSendingOperations messaging;

    @Override
    public boolean insert(ProductBidInfo productBidInfo) {
        if(productBidInfo.getBidPrice()<=getHighestValue(productBidInfo.getProductId())){
            LOGGER.error("价格低于最高价格");
            return false;
        }
        if(productBidInfoMapper.insertSelective(productBidInfo)==1){
            LOGGER.info("竞价成功");
            //广播给订阅“/topic/bidResponse”的主题
            messaging.convertAndSend("/topic/bidResponse",productBidInfo);
            LOGGER.info("广播成功");
            return true;
        }else{
            LOGGER.error("竞价失败");
        }
        return false;
    }

    @Override
    public Float getHighestValue(Integer pId) {
        ProductBidInfoExample example=new ProductBidInfoExample();
        example.createCriteria().andProductIdEqualTo(pId);
        example.setOrderByClause("bid_price desc");
        Float highestValue;
        try{
            List<ProductBidInfo> productBidInfoList=productBidInfoMapper.selectByExample(example);
            if(productBidInfoList.isEmpty()){
                highestValue=0f;
            }else{
                highestValue=productBidInfoList.get(0).getBidPrice();
            }
        }catch (Exception e){
            LOGGER.error("获取最高价格出错！");
            throw e;
        }
        return highestValue;
    }

    @Override
    public List<ProductBidInfo> loadBidInfoByProductId(Integer id) {
        ProductBidInfoExample example=new ProductBidInfoExample();
        example.createCriteria().andProductIdEqualTo(id);
        example.setOrderByClause("bid_price desc");
        return productBidInfoMapper.selectByExample(example);
    }
}
